package ExamAgain;

import java.io.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileControl {
    private static Map<String, List<Student>> studentMap = new HashMap();  //班级为键，学生集合为值


    static {
        Reader r = null;
        BufferedReader br = null;
        try {
            r = new FileReader("Test9_18/src/ExamAgain/student.txt");
            br = new BufferedReader(r);
            String s = null;
            while ((s=br.readLine())!=null){
                String[] value = s.split("\\s+");
                Student student = new Student(Integer.parseInt(value[0]),value[1],value[2], LocalDate.parse(value[3]));
                if (!studentMap.containsKey(student.getClasses())){
                    List<Student> list = new ArrayList<>();
                    list.add(student);
                    studentMap.put(student.getClasses(),list);
                }else {
                    List<Student> list = studentMap.get(student.getClasses());
                    list.add(student);
                }
            }
            System.out.println(studentMap);


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                br.close();
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String s = null;
    }

    public static void writeInfo(){
        for (String c:studentMap.keySet()) {
            Writer w = null;
            List<Student> list = studentMap.get(c);
            try {
                w = new FileWriter("Test9_18/src/ExamAgain"+c+".txt");
                for (Student s:list){
                    w.write(s.getCode()+"  "+s.getName()+"  "+s.getClasses()+"  "+s.getBirthday()+"\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    w.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public static void main(String[] args) {
        writeInfo();
    }



}
